package com.nwpu.bigdata.controller;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import com.nwpu.bigdata.dto.BackendResult;
import com.nwpu.bigdata.model.ExceptLog;
import com.nwpu.bigdata.model.FaultKey;
import com.nwpu.bigdata.model.FaultKeyExtend;
import com.nwpu.bigdata.model.User;
import com.nwpu.bigdata.service.ESLogService;
import com.nwpu.bigdata.service.FaultLogKeyService;
import com.nwpu.bigdata.service.HostService;
import com.nwpu.bigdata.service.LogMysqlService;

/**
 * @author carlin
 */
@RestController
@RequestMapping("/log")
// @SessionAttributes("currentUser")
public class LogController {
	private static Logger logger = LoggerFactory.getLogger(LogController.class);

	private final LogMysqlService logMysqlService;

	private final ESLogService esLogService;

	private final FaultLogKeyService faultLogKeyService;

	private final HostService hostService;

	private User user;

	@Autowired
	public LogController(LogMysqlService logMysqlService, ESLogService esLogService,
			FaultLogKeyService faultLogKeyService, HostService hostService) {
		this.logMysqlService = logMysqlService;
		this.esLogService = esLogService;
		this.faultLogKeyService = faultLogKeyService;
		this.hostService = hostService;
		this.user = new User();
		user.setId(1L);
		user.setUsername("admin");
		user.setEmail("grcheung@163.com");
		user.setUserPass("123456");
	}

	@GetMapping(value = "/list/{page}", consumes = "*/*", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	public BackendResult<List<ExceptLog>> listErrorLog(
			@PathVariable Long page/*
									 * ,
									 * 
									 * @ModelAttribute("currentUser") User user
									 */) {
		BackendResult<List<ExceptLog>> backendResult = logMysqlService.selectLogByPage(user.getUsername(), page);
		logger.debug("exceptLog is :{}", ReflectionToStringBuilder.toString(backendResult));
		return backendResult;
	}

	@GetMapping(value = "/list/count", consumes = "*/*", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	public BackendResult<Long> countExceptLog(/* @ModelAttribute("currentUser") User user */) {
		return new BackendResult<>(true, logMysqlService.countExceptLog(user));
	}

	@PostMapping(value = "/list/filter", consumes = "*/*", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	public BackendResult<List<ExceptLog>> filterLog(@RequestParam(value = "hostip", required = false) String hostip,
			@RequestParam(value = "software", required = false) String software,
			@RequestParam(value = "processname", required = false) String processname,
			@RequestParam(value = "keys", required = false) String keys,
			@RequestParam(value = "startTime", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") DateTime startTime,
			@RequestParam(value = "endTime", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") DateTime endTime) {
		Map<String, String[]> conditions = new ConcurrentHashMap<>();

		if (hostip != null && !"".equals(hostip)) {
			conditions.put("kubernetes.host", new String[]{hostip});
		}

		if (software != null && !"".equals(software)) {
			conditions.put("kubernetes.pod_name", new String[]{software});
		}

		if (processname != null && !"".equals(processname)) {
			conditions.put("kubernetes.container_name", new String[]{processname});
		}

		if (keys != null && !"".equals(keys)) {
			conditions.put("log", keys.split(","));
		}

		logger.info(startTime.toString("yyyy-MM-dd HH:mm:ss"));
		logger.info(endTime.toString("yyyy-MM-dd HH:mm:ss"));

		FaultKeyExtend faultKeyExtend = new FaultKeyExtend();
		faultKeyExtend.setUserId(user.getId());
		faultKeyExtend.setUser(user);
		faultKeyExtend.setKeyword(keys);
		return esLogService.getAssignLogByUser("logstash-*", "fluentd", conditions, startTime, endTime, faultKeyExtend);
	}

	@PostMapping(value = "/key/insertion", consumes = "*/*", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	public BackendResult<FaultKey> insertFaultKey(@RequestParam(value = "keys", required = true) String keys,
			@RequestParam(value = "host", required = true) String host/*
																		 * ,
																		 * 
																		 * @ModelAttribute("currentUser") User user
																		 */) {
		FaultKey faultKey = new FaultKey();
		faultKey.setKeyword(keys);
		faultKey.setHostId(hostService.getHostIdByName(host));
		faultKey.setUserId(user.getId());
		faultKey.setGmtCreate(new DateTime().toDate());
		faultKey.setGmtModified(new DateTime().toDate());
		return faultLogKeyService.setFaultLogKey(faultKey);
	}

	@GetMapping(value = "/key/list", consumes = "*/*", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	BackendResult<List<FaultKey>> listKey(/* @ModelAttribute("currentUser")User user */) {
		return faultLogKeyService.listFaultKey(user);
	}

}
